package com.moshang.blog.controller.base;

import com.google.common.collect.Maps;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.core.utils.json.JSONObject;
import com.moshang.blog.entity.Site;
import com.moshang.blog.service.UploadService;
import com.moshang.blog.core.utils.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @program: blog
 * @description: 文件上传控制器
 * @author: xieweiwei
 * @create: 2018-09-30 16:04
 **/
@RestController
@RequestMapping("file")
public class FileController {

    @Value("uploadType")
    private String uploadType;

    @Value("localUploadPath")
    private String localUploadPath;

    @Autowired
    @Qualifier("qiniuService")
    private UploadService qiniuService;

    @Autowired
    @Qualifier("ossService")
    private UploadService ossService;

    @Autowired
    @Qualifier("localUploadService")
    private UploadService localService;
    @PostMapping("upload")
    @ResponseBody
    @SystemLog("文件上传")
    public RestResponse uploadFile(@RequestParam(value = "test",required = false) MultipartFile file,@RequestParam(value = "status",defaultValue = "0",required = false)Integer status, HttpServletRequest httpServletRequest) {
        Site site = (Site)httpServletRequest.getAttribute("site");
        if(site == null){
            return RestResponse.failure("加载信息错误");
        }

        if(file == null){
            return RestResponse.failure("上传文件为空 ");
        }
        String url = null;
        Map m = Maps.newHashMap();
        try {
            if("local".equals(site.getFileUploadType())){
                url = localService.upload(file,status);
            }
            if("qiniu".equals(site.getFileUploadType())){
                url = qiniuService.upload(file,status);
            }
            if("oss".equals(site.getFileUploadType())){
                url = ossService.upload(file,status);
            }
            m.put("url", url);
            m.put("name", file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure(e.getMessage());
        }
        return RestResponse.success().setData(m);
    }

    /**
     * @param fileName
     * @param url
     * @param response
     */

    @RequestMapping("download")
    public void downLoad(@RequestParam("fileName")String fileName,@RequestParam("url")String url,@RequestParam("remoteName")String remoteName, HttpServletResponse response,HttpServletRequest httpServletRequest) throws IOException {
        URL urlStr = new URL(url);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) urlStr.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
//       String filename = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //下载的文件携带这个名称
        response.setHeader("Content-Disposition", "attachment;filename=" +new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
        //文件下载类型--二进制文件
        response.setContentType("application/octet-stream");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        OutputStream os = response.getOutputStream();
        os.write(getData);
        if (os != null) {
            os.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("info:" + url + " download success");
    }
    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    @RequestMapping("editormdPic")
    @ResponseBody
    public JSONObject editormdPic (@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception{

        //String trueFileName = file.getOriginalFilename();

       // String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        //String fileName = System.currentTimeMillis()+"_"+CommonUtils.getRandomNumber(100, 999)+suffix;

        //String path = request.getSession().getServletContext().getRealPath("/assets/msg/upload/");
        //System.out.println(path);
       String  url = ossService.upload(file,0);
//        File targetFile = new File(path, fileName);
//        if(!targetFile.exists()){
//            targetFile.mkdirs();
//        }
//
//        //保存
//        try {
//            file.transferTo(targetFile);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        JSONObject res = new JSONObject();
        res.put("url",url);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }
    @PostMapping("layUpload")
    @ResponseBody
    @SystemLog("文件上传")
    public RestResponse layUpload(@RequestParam(value = "file",required = false) MultipartFile file,@RequestParam(value = "status",defaultValue = "0",required = false)Integer status, HttpServletRequest httpServletRequest) {
        Site site = (Site)httpServletRequest.getAttribute("site");
        if(site == null){
            return RestResponse.failure("加载信息错误");
        }

        if(file == null){
            return RestResponse.failure("上传文件为空 ");
        }
        String url = null;
        Map m = Maps.newHashMap();
        try {
            if("local".equals(site.getFileUploadType())){
                url = localService.upload(file,status);
            }
            if("qiniu".equals(site.getFileUploadType())){
                url = qiniuService.upload(file,status);
            }
            if("oss".equals(site.getFileUploadType())){
                url = ossService.upload(file,status);
            }
            m.put("src", url);
            m.put("title", file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure(e.getMessage());
        }
        return RestResponse.success1().setData(m);
    }
}
